import {
  Space,
  Table,
  Pagination,
  message,
  Button,
  Modal,
  Form,
  Input,
} from 'antd';
import React, { useState, useEffect } from 'react';
import axios from 'axios';

export default () => {
  //在这里可以获取元素的DOM
  // 在函数式组件里使用useState来定义数据
  //setDate是在给data赋值的时候使用
  let [data, setDate] = useState([]);
  let [total, setTotal] = useState(0);
  let [current, setCurrent] = useState(1);
  let [pageSize, setPageSize] = useState(4);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [isModalVisible2, setIsModalVisible2] = useState(false);
  const [form2] = Form.useForm();
  let [rowid, setRowid] = useState(null);
  let [status, setStatus] = useState(1);
  const columns = [
    {
      title: '用户名',
      dataIndex: 'user_name',
      key: 'user_name',
    },
    {
      title: '用户密码',
      dataIndex: 'user_pwd',
      key: 'user_pwd',
    },
    {
      title: '用户类型',
      dataIndex: 'user_type',
      key: 'user_type',
    },
    {
      title: '用户状态',
      dataIndex: 'user_status',
      key: 'user_status',
    },
    {
      title: '操作',
      key: 'action',
      render: (text) => (
        <Space size="middle">
          {/* update.bind(this, text) 可改写为 () => {
              update(text)
            } */}
          <a
            onClick={() => {
              update(text);
            }}
          >
            update
          </a>
          <a
            style={{ color: 'red' }}
            onClick={() => {
              update2(text);
            }}
          >
            禁用/启用
          </a>
        </Space>
      ),
    },
  ];
  // 在函数挂载或即将挂载的时候调用
  useEffect(() => {
    showTable(1, 4); //当前页参数
  }, []);
  const showTable = (page, size) => {
    axios
      .get('http://localhost:3000/users', {
        params: {
          page, //当前页
          size, //一页几条
        },
      })
      .then((res) => {
        const users = res.data.result.data;
        const total = res.data.result.total;
        console.log(res);
        setTotal(total);
        // 解决antd的key值重复问题
        setDate(
          users.map((item, i) => {
            item.key = i;
            return item;
          })
        );
      });
  };
  const showTable2 = (page, size, user_name) => {
    axios
      .post(`http://localhost:3000/users/username`, {
        page, //当前页
        size, //一页几条
        user_name,
      })
      .then((res) => {
        const users2 = res.data.result.data;
        const total2 = res.data.result.total;
        setTotal(total2);
        // 解决antd的key值重复问题
        setDate(
          users2.map((item, i) => {
            item.key = i;
            return item;
          })
        );
      });
  };
  // 分页器传参
  const change = (page, pageSize) => {
    /* useState本身是异步的,所以每次都是先打印,所以就会打印出上一次选择的页码 */
    setPageSize(pageSize);
    showTable(page, pageSize); //2.显示
    setCurrent(page); //3.返回
  };
  const update = (r) => {
    setRowid(r.user_id); //获取对象的ID
    setIsModalVisible2(true);
  };
  const update2 = (r) => {
    //变更用户状态
    axios
      .put(`http://localhost:3000/users/id/status?id=${r.user_id}`, {
        user_status: 1 - r.user_status,
      })
      .then((res) => {
        if (res.status == 200) {
          message.success(res.data.message); //弹窗
          showTable(current, pageSize); //刷新页面
        } else {
          message.warning('改变用户状态失败');
        }
      });
  };
  const handleOk2 = (r) => {
    //修改用户
    //成功打印
    axios
      .put(`http://localhost:3000/users/id?id=${rowid}`, {
        user_name: r.user_name,
        user_pwd: r.user_pwd,
        user_type: r.user_type,
        user_status: r.user_status,
      })
      .then((res) => {
        if (res.status == 200) {
          message.success(res.data.message); //弹窗
          showTable(current, pageSize); //刷新页面
          setIsModalVisible2(false); //关闭表单
          form2.resetFields();
        } else {
          message.warning('修改用户失败');
        }
      });
  };
  const add = () => {
    setIsModalVisible(true);
  };
  const handleOk = (r) => {
    //成功打印
    // setIsModalVisible(false)
    axios
      .post(`http://localhost:3000/users`, {
        user_name: r.user_name,
        user_pwd: r.user_pwd,
        user_type: r.user_type,
      })
      .then((res) => {
        if (res.status == 200) {
          message.success(res.data.message); //弹窗
          showTable(current, pageSize); //刷新页面
          setIsModalVisible(false); //关闭表单
          form.resetFields();
        } else {
          message.warning('添加用户失败');
        }
      });
  };
  const onFinishFailed = () => {
    //失败打印
    message.warning('校验失败,请重试');
  };
  const handleCancel = () => {
    setIsModalVisible(false);
  };
  const handleCancel2 = () => {
    setIsModalVisible2(false);
  };
  // const query = () => {}
  const inputChange = (e) => {
    showTable2(1, 5, e.target.value);
  };
  return (
    <div>
      <Input
        style={{ marginLeft: '15px', width: '200px', display: 'inline-block' }}
        onChange={inputChange}
      ></Input>
      {/* <Button type="primary" style={{ margin: '15px' }} onClick={query}>
        查询用户
      </Button> */}
      <Button type="primary" style={{ margin: '15px' }} onClick={add}>
        增加用户
      </Button>
      <Table columns={columns} dataSource={data} pagination={false} />
      <Pagination
        current={current} //高亮选中页
        pageSize={pageSize} //控制每次刷新一页显示的条数
        defaultCurrent={1} //默认当前页
        defaultPageSize={4} //默认一页几条
        pageSizeOptions={[4, 8, 12]} //分隔页
        style={{ marginTop: '10px' }}
        total={total}
        showSizeChanger
        showQuickJumper
        onChange={change}
        showTotal={(total) => `共 ${total} 条`}
      />
      <Modal
        title="增加用户"
        visible={isModalVisible}
        footer={null}
        onCancel={handleCancel}
      >
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ remember: true }}
          onFinish={handleOk}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
          form={form}
        >
          <Form.Item
            label="用户名"
            name="user_name"
            rules={[{ required: true, message: '必填' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="密码"
            name="user_pwd"
            rules={[{ required: true, message: '必填' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="用户类型"
            name="user_type"
            rules={[
              {
                required: true,
                message: '必填,管理员(2)、交通部门(1)、普通用户(0)',
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            wrapperCol={{
              offset: 6,
              span: 16,
            }}
          >
            <Button
              type="primary"
              htmlType="submit"
              style={{ marginRight: '100px' }}
            >
              确认
            </Button>
            <Button type="primary" onClick={handleCancel}>
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title="修改用户"
        visible={isModalVisible2}
        footer={null}
        onCancel={handleCancel2}
      >
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ remember: true }}
          onFinish={handleOk2}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
          form={form2}
        >
          <Form.Item
            label="用户名"
            name="user_name"
            rules={[{ required: true, message: '必填' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="密码"
            name="user_pwd"
            rules={[{ required: true, message: '必填' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="用户类型"
            name="user_type"
            rules={[
              {
                required: true,
                message: '必填,管理员(2)、交通部门(1)、普通用户(0)',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="用户状态"
            name="user_status"
            rules={[
              {
                required: true,
                message: '必填,不禁用(1)禁用(0)',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            wrapperCol={{
              offset: 6,
              span: 16,
            }}
          >
            <Button
              type="primary"
              htmlType="submit"
              style={{ marginRight: '100px' }}
            >
              确认
            </Button>
            <Button type="primary" onClick={handleCancel2}>
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  ); //清除原有的分页使用专门的分页器
};
